package com.simpleframe.security;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.simpleframe.core.io.ClassPathResource;
import com.simpleframe.core.io.Resource;
import com.simpleframe.exception.SimpleframeException;

public class ModuleContext {

	private static ModuleContext moduleContext;
	private List<Extension> extensions;
	
	public static ModuleContext getModuleContext(){
		if(moduleContext==null){
			moduleContext = new ModuleContext();
			moduleContext.extensions = new ArrayList<Extension>();
		}
		return moduleContext;
	}
	
	public void addExtension(Extension extension){
		if(existExtension(extension)){
			throw new SimpleframeException("模块中已经存在 "+extension.getId());
			
		}
		extensions.add(extension);
	}
	
	public boolean existExtension(Extension extension){
		for (Extension ext : extensions) {
			if(ext.getId().equals(extension.getId())){
				return true;
			}
		}
		return false;
	}
	
	public Map<String, String> getResources(){
		Map<String, String> resources = new HashMap<String, String>();
		for (Extension extension : extensions) {
			List<Module> modules = extension.getModules();
			for (Module module : modules) {
				List<Action> actions = module.getActions();
				for (Action action : actions) {
					String id = extension.getId()+"_"+module.getId()+"_"+action.getId();
					System.out.println(id+":"+action.getUrl());
					resources.put(id, action.getUrl());
				}
			}
		}
		return resources;
	}
	
	public void loadModules(){
		//遍历速源码，找出那个XX
		try {
			Resource resource = new ClassPathResource("modules");
			if(!resource.exists()){
				System.out.println("系统不存在modules目录，不加载权限");
				return;
			}
			File[] files = resource.getFile().listFiles();
			for (File file : files) {
				ModuleConfigureXmlReader mcxr = new ModuleConfigureXmlReader(file);
				addExtension(mcxr.getExtension());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public static void main(String[] args) {
		ModuleContext mc = new ModuleContext();
		mc.loadModules();
		Map<String, String> map = mc.getResources();
		for (String key : map.keySet()) {
			System.out.println(key+":"+map.get(key));
		}
	}
}
